
"""
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/08/12 19:14:23 $"
"""

from traceback import print_exc
from PythonCard import model, dialog

from condition_dialog import execute_condition_dialog
from Brain.condition import CompoundCondition


class CompoundConditionDialog(model.CustomDialog):
	def __init__(self, parent, compound_condition):
		model.CustomDialog.__init__(self, parent)
		if compound_condition:
			self._compound = compound_condition.copy()
		else: self._compound = CompoundCondition()
		## populate list widget ..
		index = 0
		for statement in self._compound.enumerate():
			self.components.condition_list.append( str(statement) )
	
	def process(self):
		""" return Condition from user input
		"""
		return self._compound.copy()

	def on_add_button_mouseClick(self, event):
		""" add new condition """
		try:
			result = execute_condition_dialog(None)
			condition = result.condition
			if condition:
				result = dialog.textEntryDialog(self, 'rank bonus:', 'float input', 'if condition is true')
				if result.accepted:
					rank = float(result.text)
					element = self._compound.add_statement(condition, rank)
					self.components.condition_list.append( str(element) )
					print 'add success'
		except:
			print_exc()
			print 'add failed !'
	
	def on_edit_record_mouseClick(self, event):
		for index in self.components.condition_list.GetSelections():
			try:
				new = execute_condition_dialog( self._compound.get_statement(index).condition )
				if new.condition:
					result = dialog.textEntryDialog(self, 'rank bonus:', 'float input', 'if condition is true')
					if result.accepted:
						rank = float(result.text)
						self._compound.edit_statement(index, new.condition, rank)
						self.components.condition_list.delete(index)
						self.components.condition_list.insertItems([str(self._compound.get_statement(index))], index)
						print 'changed:', str(self._compound.get_statement(index))
						#self.components.condition_list.items[index] = str(self._compound.get_statement(index))
			except:
				print_exc()
	
	def on_delete_record_mouseClick(self, event):
		for index in self.components.condition_list.GetSelections():
			try:
				self._compound.remove_statement(index)
				self.components.condition_list.delete(index)
			except:
				print_exc()
	

def execute_compoundcondition_dialog(compound_condition):
	dlg = CompoundConditionDialog(None, compound_condition)
	result = dlg.showModal()
	if result.accepted:
		result.compound_condition = dlg.process()
	else : result.compound_condition = None
	dlg.destroy()
	return result


if __name__ == '__main__':
	class TesT(model.Background):
		pass
	
	app = model.Application(TesT, r'minimal_app.rsrc.py')
	ret = execute_compoundcondition_dialog(None)
	print ret.compound_condition








